package com.yuxi.Service.Impl;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sound.midi.MidiDevice.Info;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.mysql.jdbc.StandardSocketFactory;
import com.yuxi.Controller.UtilController;
import com.yuxi.Dao.IExcelDao;
import com.yuxi.Dao.InformationPortDao;
import com.yuxi.Dao.OwnWordRecordDao;
import com.yuxi.Entity.InformationPort;
import com.yuxi.Entity.UserInfo;
import com.yuxi.Request.InformationQuery;
import com.yuxi.Request.OwnExport;
import com.yuxi.Service.UserService;
import com.yuxi.Service.UtilService;
import com.yuxi.Util.ExportOwnWord;
import com.yuxi.Util.ExportWordUtilServlet;
import com.yuxi.excelEntity.OwnWordInfo;
import com.yuxi.excelEntity.OwnWordRecord;

@Service
public class UtilServiceImpl implements UtilService {
	@Autowired
	private IExcelDao excelDao;
	@Autowired
	private OwnWordRecordDao ownWordRecordDao;
	@Autowired
	private InformationPortDao informationPortDao;
	@Autowired
	private UserService userService;
	private Logger logger = LoggerFactory.getLogger(UtilServiceImpl.class);

	@Override
	public void exportPoliceOwn(String startTime,String endTime,HttpSession session, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			Map dataMap = new HashMap();
			UserInfo u = userService.getCurLoginUser(session);
			UserInfo uB = userService.getUserBByUserA(u);
			if (uB != null) {
				dataMap.put("userName", u.getUserName() + "," + uB.getUserName());
			} else {
				dataMap.put("userName", u.getUserName());
			}
			List<OwnWordInfo> dataSource =null;	
			
			
			
			
			List<OwnWordInfo> table1=new ArrayList<OwnWordInfo>();	
			List<OwnWordInfo> table2=new ArrayList<OwnWordInfo>();	
			List<OwnWordInfo> table3=new ArrayList<OwnWordInfo>();	
			List<OwnWordInfo> table4=new ArrayList<OwnWordInfo>();	
			List<OwnWordInfo> table5=new ArrayList<OwnWordInfo>();	
			List<OwnWordInfo> table6=new ArrayList<OwnWordInfo>();	
			List<OwnWordInfo> table7=new ArrayList<OwnWordInfo>();
			
			List<InformationPort> portDataSource=informationPortDao.getAllInfoPort();		
			InformationPort salfPort=null;
			for (Iterator iterator = portDataSource.iterator(); iterator.hasNext();) {
				InformationPort informationPort = (InformationPort) iterator.next();
				if(informationPort.getPortName().equals("生产安全")){
					salfPort=informationPort;
				}		
			}
			InformationPort jgPort=null;
			for (Iterator iterator = portDataSource.iterator(); iterator.hasNext();) {
				InformationPort informationPort = (InformationPort) iterator.next();
				if(informationPort.getPortName().equals("监管安全")){
					jgPort=informationPort;
				}		
			}
			
			List<InformationPort>  jgPortChilds=findChild(jgPort, portDataSource);
			jgPortChilds.add(jgPort);
			
			List<InformationPort>  salfPortChilds=findChild(salfPort, portDataSource);
			salfPortChilds.add(salfPort);
			
			
			String portQueryStr=getPortString(jgPortChilds,salfPortChilds);			
			
			dataSource=excelDao.outWordForInformationByIdArray(startTime,endTime,u.getUserId(),portQueryStr);
//			System.out.println(dataSource);
//			System.out.println(salfPortChilds);
//			System.out.println(jgPortChilds);
			
			for(int j=0;j<dataSource.size();j++){
				OwnWordInfo curO=dataSource.get(j);
				String curPName=curO.getPortName();
				
				Pattern pattern = Pattern.compile(".*好的做法.*");
				Matcher matcher = pattern.matcher(curPName);
				boolean b= matcher.matches();
				if(b){
					table1.add(curO);
					continue;
				}
				Pattern pattern1 = Pattern.compile(".*总体犯情.*");
				Matcher matcher1 = pattern1.matcher(curPName);
				boolean b1= matcher1.matches();
				if(b1){
					table2.add(curO);
					continue;
				}
				
				Pattern pattern2 = Pattern.compile(".*需解决的问题及情况汇报.*");
				Matcher matcher2 = pattern2.matcher(curPName);
				boolean b2= matcher2.matches();
				if(b2){
					table6.add(curO);
					continue;
				}				
				Pattern pattern3 = Pattern.compile(".*对工作的意见或建议.*");
				Matcher matcher3 = pattern3.matcher(curPName);
				boolean b3= matcher3.matches();
				if(b3){
					table7.add(curO);
					continue;
				}
				Pattern pattern4 = Pattern.compile(".*重点人头.*|.*重要时段.*|.*重点部位.*|.*重要物品.*|.*重要环节.*|.*“五重”问题.*");
				Matcher matcher4 = pattern4.matcher(curPName);
				boolean b4= matcher4.matches();
				if(b4){
					table4.add(curO);
					continue;
				}
				
				boolean isSalf=checkIsIn(Integer.parseInt(curO.getPortId()), salfPortChilds);
				if(isSalf){
					table5.add(curO);
					continue;
				}	
				boolean isJg=checkIsIn(Integer.parseInt(curO.getPortId()), jgPortChilds);
				if(isJg){
					table3.add(curO);
				}
				
			}
			
			String Time=startTime+"~"+endTime;
			dataMap.put("time", Time);
			dataMap.put("table1", table1);
			dataMap.put("table2", table2);
			dataMap.put("table3", table3);
			dataMap.put("table4", table4);		
			dataMap.put("table5", table5);
			dataMap.put("table6", table6);
			dataMap.put("table7", table7);
			dataMap.put("comment", "${comment}");
			String filUrl=request.getServletContext().getRealPath("/");
			String realPath = filUrl + "UploadWord\\";
			String fileName = Long.toString(System.currentTimeMillis());
		
			ExportOwnWord exp = new ExportOwnWord(realPath, fileName);
			System.out.println(realPath);
			ExportWordUtilServlet exs = new ExportWordUtilServlet();
			exs.importExcel(dataMap, "民警个人情况汇报表", request, response);
			exp.createDoc(dataMap);
			exp.createHTML(dataMap);			
			String url = request.getScheme() + "://";
			url+= request.getHeader("host");
			
			String base="/UploadWord/"+fileName;		
			OwnWordRecord oRecord = new OwnWordRecord(base+".doc", base+".html", "", u.getUserId(),
					u.getUserName(), userService.curLoginUserPowerView(session).getMaxStructure().getId());
			oRecord.setBaseAddress(filUrl);
			if (uB != null) {
				oRecord.setUserBName(uB.getUserName());
				oRecord.setUserBId(uB.getUserId());
			}
			ownWordRecordDao.add(oRecord);
			logger.info("生成民警个人情况表成功");
		} catch (IOException e) {
			logger.error("生成民警个人情况表失败");
		}
	}
		
	private String getPortString(List<InformationPort> pList1,List<InformationPort> pList3){
		StringBuffer portStr=new StringBuffer();
		List<InformationPort> pList2=new ArrayList<InformationPort>();
		pList2.addAll(pList1);
		pList2.addAll(pList3);
		Integer index=0;
		for (Iterator iterator = pList2.iterator(); iterator.hasNext();) {
			InformationPort informationPort = (InformationPort) iterator.next();
			if(index>=1){
				portStr.append(",");
			}
			portStr.append(informationPort.getId());
			index++;
			
		}
		return portStr.toString();		
	}
	@Override
	public boolean ownWordComment(Integer id,String comment) {
		try{
			OwnWordRecord oRecord=ownWordRecordDao.get(id);
			String base=oRecord.getBaseAddress();
			String dN=oRecord.getWordAddress();
			String Hn=oRecord.getHtmlAddress();	
			String name=dN.substring(dN.lastIndexOf("/"), dN.lastIndexOf("."));		
			ExportOwnWord exp = new ExportOwnWord(base+"UploadWord\\",name);
			Map dataMap = new HashMap();
			dataMap.put("comment", comment);
			exp.temFlase=true;
			exp.temUrl=new File(base);
			exp.docName=dN;
			exp.htmlName=Hn;
			exp.createDoc(dataMap);
			exp.createHTML(dataMap);
			oRecord.setState((short)1);			
			ownWordRecordDao.modify(oRecord);
			return true;
		}catch(Exception e ){
			return false;
		}
		
	}
	@Override
	public  List<InformationPort> findChild(InformationPort x,List<InformationPort> source){
		
	try{
		List<InformationPort> rs=new ArrayList<InformationPort>();
		Integer portId=x.getId();
		Iterator<InformationPort> it=source.iterator();
		while(it.hasNext()){
			InformationPort cur=it.next();
			if(cur.getSuperId()==portId){
				rs.add(cur);				
				rs.addAll(findChild(cur,source));
			}
		}
		return rs;
	}catch(Exception e){
		List<InformationPort> rs=new ArrayList<InformationPort>();
		return rs;
	}
	}
	
	public boolean checkIsIn(Integer itemId,List<InformationPort> data){
		
		try{

			for (Iterator iterator = data.iterator(); iterator.hasNext();) {
				InformationPort informationPort = (InformationPort) iterator.next();
				if(informationPort.getId()==itemId){
					return true;
				}
			}
		}catch(Exception e){
			return false;
		}
		
		return false;
	}

}
